#! /bin/env python

import ConfigParser
from MySQLdb import connect, cursors
import os
import sys
from xml.dom.minidom import Document, parse, parseString, Node
from BeautifulSoup import BeautifulSoup as Soup
from subprocess import *

def getStationInfo(node) :
    id = node.getElementsByTagName('id')[0].firstChild.data
    name = node.getElementsByTagName('name')[0].firstChild.data
    mobileno = node.getElementsByTagName('mobileno')[0].firstChild.data
    return id, name, mobileno

def handleStationDom(dom) :
    stations = dom.getElementsByTagName('station')
    for station in stations :
        bus = station.getElementsByTagName('bus')
        
        if len(bus) :
            color = bus[0].getElementsByTagName('color')[0].firstChild.data
            id, name, mobileno = getStationInfo(station)
            
            print id, name, mobileno
            prev = station.previousSibling
            next = station.nextSibling
            if prev != None :
                p_id, p_name, p_mobileno = getStationInfo(prev) 
                print p_id, p_name, p_mobileno
            if next != None :
                n_id, n_name, n_mobileno = getStationInfo(next) 
    
            
def processFetch(busList) :
    for busInfo in busList :
        bus_no = busInfo[0]
        route_id  = busInfo[1]
        """
        fetch_pipe =Popen("wget 'http://m.gbis.go.kr/jsp/routeInfo.jsp?routeId=" + str(route_id)+"' -O " + bus_no, stdout=PIPE, stdin=PIPE, shell=True)
        
        fetch_pipe.stdout.close()
        toxml_pipe = Popen("./stationList.py " + bus_no, stdin=PIPE, stdout=PIPE, shell=True)
        station_xml = toxml_pipe.stdout.read()
        toxml_pipe.stdout.close()

        #os.system("rm " + bus_no)
        """
        pipe = Popen("cat 9404.xml", stdout=PIPE, shell=True)
        station_xml = pipe.stdout.read()
        dom = parseString(station_xml)
        handleStationDom(dom)


def getBusListForRequest(cursor) :
    cursor.execute('SELECT bus_no FROM REQUEST')
    bus_nos = cursor.fetchall()
    
    busList = []
    for bus_no in bus_nos :
        cursor.execute('SELECT bus_no, route_id FROM BUS_INFO WHERE bus_no="' + bus_no[0]+'"')
        bus_info = cursor.fetchone()
        if bus_info is not None :
            busList.append(bus_info)
    
    return busList

def getConnection() :
    config = ConfigParser.RawConfigParser();
    config.read(['db.cfg', os.path.expanduser('/var/www/html/db.cfg')])
    
    host_name = config.get("mysqld", "host_name")
    user_name = config.get("mysqld", "user_name")
    db_name = config.get("mysqld", "db_name")
    db_password = config.get("mysqld", "db_password")
    return connect(host=host_name, user=user_name, passwd=db_password, db=db_name)

    
def main() :
	# 1. DB Config
    conn = getConnection()
    cursor = conn.cursor()
    # 2. get url list
    busList = getBusListForRequest(cursor)
    processFetch(busList)

if __name__ == "__main__":
    main()
